﻿using System.Reflection;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using Autofac;
using Autofac.Integration.Mvc;
using GC_RF.Domain.Helpers;
using GC_RF.Site.Modules.Autofac;

namespace GC_RF.Site
{
	public class MvcApplication : HttpApplication
	{
		#region Variables

		private IContainer _diContainer;

		#endregion

		#region Methods

		protected void Application_Start()
		{
			AreaRegistration.RegisterAllAreas();
			FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
			RouteConfig.RegisterRoutes(RouteTable.Routes);
			BundleConfig.RegisterBundles(BundleTable.Bundles);

			var builder = new ContainerBuilder();

			builder.RegisterControllers(Assembly.GetExecutingAssembly()).PropertiesAutowired();
			builder.RegisterModule(new SiteModule());

			_diContainer = builder.Build();

			DependencyResolver.SetResolver(new AutofacDependencyResolver(_diContainer));
		}

		protected void Application_Error()
		{
			var exception = Server.GetLastError();
			if (exception == null)
				return;

			Server.ClearError();
			Response.Clear();

			ApplicationLogger.Logger.LoggingExceptionMessage(exception);

			var url = UrlHelper.GenerateUrl("Default", "Error", "Error", null, RouteTable.Routes, Request.RequestContext, false);
			if (url != null)
				Response.Redirect(url, false);
		}

		protected void Application_Disposed()
		{
			if (_diContainer != null)
				_diContainer.Dispose();
		}

		#endregion
	}
}
